var app = getApp()
var util = require("../utils/util.js");
var location = require('../utils/location.js');
var config = require("../utils/config.js");
var API_URL = config.API_URL;
var TABBAR_URL = config.TABBAR_URL;
var storeInfo = {}, userInfo = {};

function init(that) {
  that.setData({
    mobilePhone: "",
    password: "",
    confirmPassword: "",
    verifyCode: ""
  })
  location.get(that);
}

function checkUserMobilePhone(that) {
  var mobilephone = that.data.mobilePhone;
  if (mobilephone == "") {
    wx.showModal({
      title: '提示',
      content: "手机号不能为空！",
      showCancel: false
    })
    return false;
  }
  else if (!util.checkMobilePhone(mobilephone)) {
    wx.showModal({
      title: '提示',
      content: "手机号码有误，请重填！",
      showCancel: false
    })
    return false;
  }
  return true;
}

function checkAccount(that) {
  var account = that.data.account;
  var notMobile = !util.checkMobilePhone(account);
  var notEmail = !util.checkEmail(account)
  if (account == "") {
    wx.showModal({
      title: '提示',
      content: "手机号或邮箱号不能为空！",
      showCancel: false
    })
    return false;
  }else if (notMobile && notEmail) {
    wx.showModal({
      title: '提示',
      content: "请输入正确的手机号或邮箱号",
      showCancel: false
    })
    return false;
  }
  return true;
}

function setAccount(e,that){
  console.log(e);
  that.setData({
    account: e.detail.value
  })
}

// 登录
function login(that, cb) {
  if (that.data.item.busy) {
    return
  }
  var item = that.data.item;
  item.busy = true;
  that.setData({ item: item })
  setTimeout(function () {
    console.log("----->>>用户登录中...");
    var account = that.data.account;
    var userPassword = that.data.password;
    storeInfo = wx.getStorageSync('store');
    that.setData({
      loading: true
    })
    if (!checkAccount(that)) {
      item.busy = false;
      item.loading = false;
      that.setData({ item: item })
      return
    }
    if (userPassword == "") {
      console.log("密码不能为空！");
      wx.showModal({
        title: '提示',
        content: "密码不能为空！",
        showCancel: false
      })
      item.busy = false;
      item.loading = false;
      that.setData({ item: item })
      return;
    }
    wx.login({
      success: function (res) {
        console.log(res);
        console.log("----->>>用户帐号:" + account);
        console.log("----->>>用户密码:" + userPassword);
        console.log("----->>>用户登录码:" + res.code);
         wx.request({
          url: API_URL.login,
          data: {
            loginCode: res.code,
            account: account,
            password: userPassword,
            tag: 'jadebox',
          },
          method: 'POST',
          success: function (res) {
            console.log("----->>>请求登录接口成功！");
            console.log(res)
            if (res.data.status == 200) {
              console.log(res.data.responseData.session);
              wx.setStorageSync('session', res.data.responseData.session);
              wx.showToast({
                title: "登录成功",
                icon: 'success',
                duration: 1000
              });
              userInfo = {
                id: res.data.responseData.userId,
                identity: res.data.responseData.identity,
                openId: res.data.openid,
                account: that.data.account,
              }
              wx.setStorageSync('user', userInfo);
              typeof cb == "function" && cb(userInfo, that)
            } else {
              wx.showModal({
                title: '提示',
                content: res.data.msg,
                showCancel: false
              })
              return;
            }
          },
          fail: function () {
            util.showNotice('请求超时')
          },
          complete: function () {
            item.busy = false;
            item.loading = false;
            that.setData({ item: item })
          }
        }); 
      },
      fail: function () {
        console.log("请求登录接口失败！");
        wx.showModal({
          title: '提示',
          content: "网络出问题了！",
          showCancel: false
        })
        item.busy = false;
        item.loading = false;
        that.setData({ item: item })
        return;
      }
    });
  }, 200)
}

function getCode(that, second) {
  var item = that.data.item;
  var account = that.data.account;
  if (!checkAccount(that)) {
  } else {
    wx.request({
      url: API_URL.sendCode,
      data: { account: account, tag: 'jadebox' },
      method: 'POST',
      success: function (res) {
        if (res.data.status == 200) {
          wx.showToast({
            title: '发送成功',
            icon: 'success',
            duration: 800
          })
          item.code = second;
          item.disabled = true;
          that.setData({
            item: item
          });
          second--;
          countdown(that, second)
        } else {
          util.showNotice(res.data.msg)
        }
      },
      fail: function () {
        wx.showModal({
          title: '提示',
          content: "网络错误",
          showCancel: false
        })
      }
    })
  }
}

function countdown(that, second) {
  var item = that.data.item;
  if (second < 0) {
    item.code = '重新获取';
    item.disabled = false;
    item.busy = that.data.item.busy;
    that.setData({
      item: item
    });
    return;
  }
  var time = setTimeout(function () {
    item.code = second--;
    item.busy = that.data.item.busy;
    that.setData({
      item: item
    });
    countdown(that, second);
  }, 1000)
}

function goReg(that) {
  var template = that.data.template;
  template.name = 'register';
  that.setData({
    template: template
  })
}

function goLogin(that) {
  var template = that.data.template;
  template.name = 'login';
  that.setData({
    template: template
  })
}

function protocol() {
  wx.navigateTo({
    url: '/pages/protocol/protocol'
  })
}

function password(e, that) {
  console.log(e)
  that.setData({
    password: e.detail.value
  })
}

function checkPassword(that) {
  var password = that.data.password;
  var confirmPassword = that.data.confirmPassword;
  if (password == "") {
    console.log("密码不能为空！");
    wx.showModal({
      title: '提示',
      content: "密码不能为空！",
      showCancel: false
    })
    return false;
  } else if (confirmPassword == '') {
    wx.showModal({
      title: '提示',
      content: "确认密码不能为空！",
      showCancel: false
    })
    return false;
  }
  if (password != confirmPassword) {
    wx.showModal({
      title: '提示',
      content: '两次输入的密码不一样',
      showCancel: false
    })
    return false;
  }
  return true;
}

function checkVerifyCode(that) {
  var verifyCode = that.data.verifyCode;
  if (verifyCode == "") {
    console.log("验证码不能为空");
    wx.showModal({
      title: '提示',
      content: "验证码不能为空！",
      showCancel: false
    })
    return false;
  }
  return true;
}

function register(e, that, cb) {
  wx.showToast({
    title: '注册中',
    icon: 'loading',
    duration: 10000,
    mask: true
  })
  if (that.data.item.busy) {
    return
  }
  var item = that.data.item;
  item.busy = true;
  that.setData({ item: item })
  setTimeout(function () {
    var input = e.detail.value;
    var account = input.account;
    var password = that.data.password;
    var confirmPassword = that.data.confirmPassword;
    var verifyCode = that.data.verifyCode;
    if (checkPassword(that) && checkAccount(that) && checkVerifyCode(that)) {
      wx.login({
        success: function (res) {
          console.log("account:" + account);
          console.log("verifyCode:" + verifyCode);
          console.log("password:" + password);
          console.log("loginCode:" + res.code);
          wx.request({
            url: API_URL.register,
            data: {
              account: account,
              verifyCode: verifyCode,
              password: password,
              loginCode: res.code,
              tag: 'jadebox',
              latitude: that.data.latitude,
              longitude: that.data.longitude,
              address: that.data.address
            },
            method: 'POST',
            success: function (res) {
              console.log(res)
              if (res.data.status == 200) {
                wx.setStorageSync('session', res.data.responseData.session);
                wx.showToast({
                  title: "登录成功",
                  icon: 'success',
                  duration: 1000
                });
                userInfo = {
                  id: res.data.responseData.userId,
                  openId: res.data.responseData.openid,
                  store_name: res.data.responseData.store_name,
                  box_number: res.data.responseData.box_number
                };
                wx.setStorageSync('user', userInfo);
                typeof cb == "function" && cb(userInfo, that)
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.msg,
                  showCancel: false
                })
              }
            },
            fail: function () {
              console.log("注册错误")
              wx.showModal({
                title: '提示',
                content: '请求超时',
                showCancel: false
              })
            },
            complete: function () {
              wx.hideToast();
              item.busy = false;
              item.loading = false;
              that.setData({ item: item })
              console.log('完成');
            }
          })
        }
      })
    } else {
      wx.hideToast();
      item.busy = false;
      item.loading = false;
      that.setData({ item: item })
    }
  }, 200)
}

module.exports = {
  init: init,
  login: login,
  getCode: getCode,
  goReg: goReg,
  goLogin: goLogin,
  protocol: protocol,
  password: password,
  checkPassword: checkPassword,
  register: register,
  checkUserMobilePhone: checkUserMobilePhone,
  checkAccount: checkAccount,
  setAccount: setAccount
}